package com.atguigu.spzx.manner.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.atguigu.spzx.manner.service.ValidateCodeService;
import com.atguigu.spzx.model.vo.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import java.io.ByteArrayOutputStream;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    private static final int WIDTH = 120;
    private static final int HEIGHT = 40;
    private static final int CODE_LENGTH = 4;
    private static final int EXPIRE_MINUTES = 5;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public ValidateCodeVo generateValidateCode() {
        // 1. 使用Hutool生成图形验证码
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(WIDTH, HEIGHT, CODE_LENGTH, 20);

        // 2. 获取验证码和Base64图像
        String code = captcha.getCode();
        String imageBase64 =captcha.getImageBase64Data();

        // 3. 生成唯一key并存入Redis
        String uuid = IdUtil.simpleUUID();
        redisTemplate.opsForValue().set(
            "captcha:" + uuid,
            code,
            EXPIRE_MINUTES,
            TimeUnit.MINUTES
        );

        return new ValidateCodeVo(uuid, imageBase64);
    }


}
